package com.hctforgreen.greenservice.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hctforgreen.greenservice.EntryCatalogActivity;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.ResultEntity;

import java.io.File;

public class EntryCatalogUtil {

    public boolean startEntryCatalogActivity(Activity activity, BookEntity entity, boolean needDownload) throws Exception {
        LogUtil.e("pm", "download:startEntryCatalogActivity:" + JSON.toJSONString(entity) + "\nneedDownload=" + needDownload);
        DbController dbController = new DbController(activity);
        BookEntity inDbEntity = dbController.getBookEntityUseBookName(entity.bookName);
        String local = BookEntity.inDbCopyFileName(inDbEntity, BookEntity.Format.ZIP, activity);
        LogUtil.e("pm", "download:path=" + local + "\ninDbEntity=" + JSON.toJSONString(inDbEntity));
        if (local != null && new File(local.replace(".zip", "")).exists()) {
            try {
                if (local.endsWith(".zip")) {
                    Intent intent = getStartEntryCatalogIntent(activity, entity);
                    activity.startActivity(intent);
                    addClickCount(activity, entity.bookName);
                    addClickRecord(activity, entity.bookName);
                } else {
                    Intent intent = getOfficeInetnt(activity, local);
                    activity.startActivity(intent);
                    addClickCount(activity, entity.bookName);
                }
                Utils.submitPoints(activity, 2, "", false);// 增加积分
            } catch (Exception e) {
                if (e instanceof ActivityNotFoundException) {
                    //出现异常的情况有：getOfficeInetnt在寻找手机上安装的第三方软件没有找到 ActivityNotFoundException
                    //弹框提示 20161123 390697
                    Toast.makeText(activity, R.string.no_app_can_be_used, Toast.LENGTH_LONG).show();
                }
                e.printStackTrace();
            }
            return true;
        } else {
            if (!needDownload) {
                //不需要下载这份资料
                if (local == null) {
                    return false;
                }
            }
            if (inDbEntity.bookZipState.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_ING)) {
                //正在下载这份资料
                Toast.makeText(activity, activity.getString(R.string.downloading_wait_hint), Toast.LENGTH_SHORT).show();
                return false;
            }
            if (inDbEntity.bookZipState.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_ING)) {
                //资料已经下载完毕
                Toast.makeText(activity, activity.getString(R.string.analysising_wait_hint), Toast.LENGTH_SHORT).show();
                return false;
            }
            DownloadUtil downloadUtil = new DownloadUtil();
            //0未下载   1下载文件不存在
            if (local == null) {
                //如果不存在，需要去下载
                downloadUtil.makeSureDownloadDiaolg(activity, inDbEntity, 0);
            } else {
                inDbEntity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE;
                dbController.updateBookZipState(inDbEntity);
                downloadUtil.makeSureDownloadDiaolg(activity, inDbEntity, 1);
            }
            return false;
        }
    }


    public Intent getOfficeInetnt(Context context, String local) {
        //使用第三方的应用打开资料
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(local));
        //找支持该种类型的软件 getFileType
        intent.setDataAndType(uri, getFileType(local));
        return intent;
    }

    public String getFileType(String path) {
        String fileType = "";
        /**
         * 2016-10-04
         * 390694
         * 添加后缀为“.docx”格式的Word资料和“.pptx”格式的PPT资料
         */
        if (path.endsWith(".doc") || path.endsWith(".docx")) {
            fileType = "application/msword";
        } else if (path.endsWith(".pdf")) {
            fileType = "application/pdf";
        } else if (path.endsWith(".xls") || path.endsWith(".xlsx")) {
            fileType = "application/vnd.ms-excel";

        } else if (path.endsWith(".ppt") || path.endsWith(".pptx")) {
            fileType = "application/vnd.ms-powerpoint";
        }
        return fileType;
    }

    /**
     * @param activity
     * @param entity
     * @return
     */
    public Intent getStartEntryCatalogIntent(Context activity, BookEntity entity) {
        Intent intent = new Intent();
        intent.setClass(activity, EntryCatalogActivity.class);
        // intent.putExtra(HctConstants.ON_ZIP_SDCARD_PATH_KEY, local);
        if (entity.bCanUpdate.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {
            intent.putExtra(HctConstants.ON_ACTIVITY_KEY_CURRENT_BOOK_ID, entity.currentBookId);
            intent.putExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID, "");
        } else {
            intent.putExtra(HctConstants.ON_ACTIVITY_KEY_CURRENT_BOOK_ID, "");
            intent.putExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ID, entity.id);
        }
        intent.putExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_TYPE_NAME, entity.booktypeName);
        intent.putExtra(HctConstants.ON_ACTIVITY_KEY_ENTRY_TITLE_CONTENTS, "");
        intent.putExtra(HctConstants.ON_ACTIVITY_KEY_SEARCH_MACHINE_NAME, "");
        intent.putExtra(HctConstants.ON_ACTIVITY_KEY_DISPLAY_NAME, entity.displayName);
        return intent;
    }

    private void addClickRecord(final Activity activity, final String bookName) {
        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        hctResult = (HctResult) msg.obj;
                        ResultEntity entity = (ResultEntity) hctResult.data;
                        break;
                    case HctConstants.STATUS_FAILD:
                        break;
                }
            }

        };
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(activity);
                    HctResult result = controller.addClickRecord(bookName, LoginResultStoreUtil.get(activity).personId);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }

    private void addClickCount(final Activity activity, final String bookName) {

        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        hctResult = (HctResult) msg.obj;
                        ResultEntity entity = (ResultEntity) hctResult.data;
                        break;
                    case HctConstants.STATUS_FAILD:
                        break;
                }
            }

        };
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(activity);
                    HctResult result = controller.addClickCount(bookName);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }
}
